package aliyun

import (
	"engine/dto"
	"errors"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/goccy/go-json"
	"lib/log"
)

type SmsService struct {
	SignName        string
	TemplateCode    string
	TemplateParam   map[string]string
	PhoneNumbers    string
	AccessKeyId     string
	AccessKeySecret string
}

func (smsService *SmsService) Init() error {
	aliConfig, err := dto.GetAliConfig()
	if err != nil {
		log.Errorf("GetAliConfig err: %s", err.Error())
		return err
	}
	if aliConfig == nil {
		return errors.New("AliConfig Error")
	}
	smsService.AccessKeyId = aliConfig.AccessKeyId
	smsService.AccessKeySecret = aliConfig.AccessKeySecret
	return nil
}

func (smsService *SmsService) SendMsg() (error error) {
	acsClient, error := sdk.NewClientWithAccessKey("", smsService.AccessKeyId, smsService.AccessKeySecret)
	if error != nil {
		log.Errorf("(smsService *SmsService) SendMsg() csClient, error := sdk.NewClientWithA err %v", error)
		return
	}
	// 创建API请求并设置参数
	request := requests.NewCommonRequest()
	request.Method = "POST"
	request.Domain = "dysmsapi.aliyuncs.com"
	request.Version = "2017-05-25"
	request.ApiName = "SendSms"
	request.QueryParams["PhoneNumbers"] = smsService.PhoneNumbers
	request.QueryParams["SignName"] = smsService.SignName
	request.QueryParams["TemplateCode"] = smsService.TemplateCode
	if smsService.TemplateParam != nil {
		TemplateParam, _ := json.Marshal(smsService.TemplateParam)
		request.QueryParams["TemplateParam"] = string(TemplateParam)
	}

	// 发送请求并获取响应
	respones, error := acsClient.ProcessCommonRequest(request)
	if error != nil {
		log.Errorf("(smsService *SmsService) SendMsg() respones, error = %v", error)
		return
	}
	responesStr, error := json.Marshal(respones)
	log.Errorf("(smsService *SmsService) SendMsg() respones, error = %v", responesStr)
	return
}

func (smsService *SmsService) SendOrderMsg() (error error) {
	jsonStr, _ := json.Marshal(smsService.TemplateParam)
	log.Errorf("(smsService *SmsService) SendOrderMsg() sonStr, _ := json.Marshal(smsService.TemplateParam), error = %v", jsonStr)

	smsService.Init()
	if smsService.SignName == "" {
		smsService.SignName = "惠养天成"
	}
	if smsService.TemplateCode == "" {
		smsService.TemplateCode = "SMS_463705045"
	}
	error = smsService.SendMsg()
	return error
}

func (smsService *SmsService) SendRandMsg(phone, rand string) (error error) {
	jsonStr, _ := json.Marshal(smsService.TemplateParam)
	log.Errorf("(smsService *SmsService) SendOrderMsg() sonStr, _ := json.Marshal(smsService.TemplateParam), error = %v", jsonStr)

	sendMsg := map[string]string{}
	sendMsg["code"] = rand

	smsService.SignName = "无双联创网络科技"
	smsService.TemplateCode = "SMS_463705045"
	smsService.PhoneNumbers = phone
	smsService.AccessKeyId = "LTAI5t9K6hgZBdgfNjr19oiG"
	smsService.AccessKeySecret = "VLKzeRtzIIo3N7zJKGo0WchwMXdjAe"
	smsService.TemplateParam = sendMsg
	return smsService.SendMsg()
}
